﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Community.IMode;
using FantastPlatform.Community.IService;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Core;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework.IModel;
using Newtonsoft.Json;
using FantastPlatform.Framework.Model;

namespace FantastPlatform.Community.UI.Service
{
    public partial class ResponsibilityAreaStreet : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //IResponsibilityAreaStreetService responsibilityAreaStreetService;
            IPoliceStreetService policestreetService;
            Condition enableCondition = new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true };
            ConditionGroup group = new ConditionGroup();
            group.Conditions.Add(enableCondition);
            switch (Action)
            {
                case "Add":
                    string data = Data;
                    ResponsibilityAreaStreetView areaStreetView = JsonToEntity<ResponsibilityAreaStreetView>(RepairString(data));
                    policestreetService = ServiceFactory.CreateService<IPoliceStreetService>();

                    //policestreetService = ServiceFactory.CreateService<IPoliceStreetService>();
                    if (areaStreetView.Id == 0)
                    {
                        policestreetService.AddStreet(areaStreetView.PoliceMan, areaStreetView.StreetId);
                        ReturnSuccessMessage("添加社区民警负责街道成功");
                    }
                    else
                    {
                        int t=0;
                        group.Conditions.Add(new Condition() { Field = "PoliceMan.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = areaStreetView.Id });
                        group.Conditions.Add(new Condition() { Field = "Street.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = areaStreetView.StreetId });
                        policestreetService.Search(group, null, Int32.MaxValue, 1, out t);
                        if (t > 0)
                        {
                            ReturnErrorMessage("已有该记录！");
                        }
                        else
                        {
                            IPoliceStreet policeStreet = policestreetService.Get(areaStreetView.Id);
                            policeStreet.PoliceMan = new Employee();
                            policeStreet.Street = new Street();
                            policeStreet.Id = areaStreetView.Id;
                            policeStreet.PoliceMan.Id = areaStreetView.PoliceMan;
                            policeStreet.Street.Id = areaStreetView.StreetId;
                            policeStreet.Enable = true;
                            policeStreet.ModifyDate = DateTime.Now;
                            policestreetService.Update(policeStreet);
                            ReturnSuccessMessage("更新社区民警负责街道成功");
                        }
                    }
                    break;
                case "Search":
                    int totalCount = 0;
                    IOrganization org = LoginEmployee.EmployeePosts[0].Post.Organization;
                    policestreetService = ServiceFactory.CreateService<IPoliceStreetService>();
                    if (LoginEmployee != null)
                    {
                        if (LoginEmployee.User != null)
                        {
                            IList<IRole> roleList = LoginEmployee.User.Roles;
                            List<string> roles = new List<string>();
                            foreach (IRole role in roleList)
                            {
                                roles.Add(role.Name);
                            }
                            if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
                            {
                            }
                            else if (roles.Contains("社区二级管理员"))
                            {
                                group.Conditions.Add(new Condition() { Field = "PoliceMan.EmployeePosts.Post.Organization.Parent.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = org.Id });
                            }
                            else
                            {
                                group.Conditions.Add(new Condition() { Field = "PoliceMan.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = LoginEmployee.Id });
                            }
                        }
                    }
                    IList<IPoliceStreet> policeStreetList = policestreetService.Search(group, null, PageSize, SelfPage, out totalCount);
                    //IOrganizationService orgService = ServiceFactory.CreateService<IOrganizationService>();
                    //IList<IOrganization> list = orgService.Search(group, null, PageSize, SelfPage, out totalCount);
                    object[] objArr = (from o in policeStreetList
                                       select new
                                       {
                                           Id = o.Id,
                                           ResponsibilityArea = (from p in o.PoliceMan.EmployeePosts
                                                                 where p.Enable == true
                                                                 select p).FirstOrDefault().Post.Organization.Name,
                                           Street = o.Street.Name,
                                           PoliceMan = o.PoliceMan.Name
                                           //Street = o.Street == null ? "" : o.Street.Name
                                       }
                                     ).ToArray();

                    ReturnList(PageSize, totalCount, objArr);

                    break;
                case "SearchStreetByResponsibilityAreaId":
                    totalCount = 0;
                    int responsibilityAreaId = Int32.Parse(Request.QueryString["responsibilityAreaId"]);
                    //IList<IResponsibilityAreaStreet> list = GetResponsibilityAreaStreetsByAreaID(responsibilityAreaId, out totalCount);
                    group.Conditions.Add(new Condition() { Field = "PoliceMan.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = LoginEmployee.Id });
                    policestreetService = ServiceFactory.CreateService<IPoliceStreetService>();
                    policeStreetList = policestreetService.Search(group, null, PageSize, SelfPage, out totalCount);
                    objArr = (from o in policeStreetList
                              select new
                              {
                                  Id = o.Street.Id,
                                  Code = o.Street.Code,
                                  Name = o.Street.Name,
                              }
                                    ).ToArray();

                    ReturnList(PageSize, totalCount, objArr);

                    break;
                case "Get":
                    try
                    {
                        policestreetService = ServiceFactory.CreateService<IPoliceStreetService>();
                        IPoliceStreet ps = policestreetService.Get(Id);

                        object obj = new
                        {
                            Id = ps.Id,
                            OrganizationId = ps.PoliceMan == null ? 0 : (from p in ps.PoliceMan.EmployeePosts
                                                                               where p.Enable == true
                                                                               select p).FirstOrDefault().Post.Organization.Id,
                            StreetId = ps.Street == null ? 0 : ps.Street.Id,
                             StreetName = ps.Street == null ?  "":ps.Street.Id+"|"+ ps.Street.Name,
                            PoliceMan = ps.PoliceMan.Id
                        };

                        ReturnObj(obj);

                    }
                    catch (Exception ex)
                    {
                        //ReturnErrorMessage(ex.Message);
                    }
                    break;
                case "SearchResponsibilityArea":

                    int total = 0;
                    IOrganizationService ogranizationService = ServiceFactory.CreateService<IOrganizationService>();
                    Condition nameCodidton = new Condition() { Field = "Name", Type = typeof(string).FullName, Value1 = "%责任区", Comparison = Comparisons.Like };
                    group.Conditions.Add(nameCodidton);
                    IList<IOrganization> orglist = ogranizationService.Search(group, null, PageSize, SelfPage, out total);

                    object[] objArr2 = (from o in orglist
                                        select new
                                        {
                                            Id = o.Id,
                                            Code = o.Code,
                                            Name = o.Name
                                        }
                                     ).ToArray();
                    //string jsonStrs = JsonConvert.SerializeObject(objArr);
                    //jsonStrs = "{'totalCount':'" + totalCount.ToString() + "','topics':" + jsonStrs + "}";
                    //Response.Write(jsonStrs);
                    //Response.End();
                    ReturnList(total, objArr2);
                    break;
                case "GetStreets":

                    string code = "";
                    if (!string.IsNullOrEmpty(Request["code"]))
                    {
                        code = Request["code"];
                    }
                    totalCount = 0;
                    IList<IOrganization> organizationList = new List<IOrganization>();
                    GetOrganization(LoginEmployee.EmployeePosts[0].Post.Organization, organizationList);

                    // IOrganization org = ServiceFactory.CreateService<IOrganizationService>().Get(58);
                    // GetOrganization(org, organizationList);

                    IList<IStreet> areaStreetlist = new List<IStreet>();
                    foreach (IOrganization item in organizationList)
                    {
                        foreach (IPoliceStreet areaStreet in GetResponsibilityAreaStreetsByPoliceID(item.Id, out totalCount))
                        {
                            areaStreetlist.Add(areaStreet.Street);
                        }
                    }
                    IStreetService streetService = ServiceFactory.CreateService<IStreetService>();
                    IList<IStreet> list3 = streetService.SearchStreet(code, PageSize, SelfPage, out totalCount);

                    objArr = (from o in list3
                              where !areaStreetlist.Contains(o)
                              select new
                              {
                                  Id = o.Id,
                                  Code = o.Code,
                                  Name = o.Name
                              }
                                    ).ToArray();
                    ReturnList(totalCount, objArr);

                    break;
                case "AddStreet":

                    string areaId = "";
                    if (!string.IsNullOrEmpty(Request.QueryString["ResponsibilityAreaId"]))
                    {
                        areaId = Request.QueryString["ResponsibilityAreaId"];
                    }
                    if (string.IsNullOrEmpty(Data))
                    {
                        throw new Exception("传入的选中用户Id为空");
                    }
                    string[] idruStrList = Data.Split(',');
                    foreach (string id in idruStrList)
                    {
                        policestreetService = ServiceFactory.CreateService<IPoliceStreetService>();
                        policestreetService.AddStreet(Int32.Parse(areaId), Int32.Parse(id));
                    }
                    ReturnSuccessMessage("添加街道成功");
                    break;
                case "RemoveStreet":
                    try
                    {
                        string areaId2 = "";
                        if (!string.IsNullOrEmpty(Request.QueryString["ResponsibilityAreaId"]))
                        {
                            areaId2 = Request.QueryString["ResponsibilityAreaId"];
                        }
                        if (string.IsNullOrEmpty(Data))
                        {
                            throw new Exception("传入的选中用户Id为空");
                        }
                        List<int> idruList = new List<int>();
                        string[] idruStrList2 = Data.Split(',');
                        foreach (string id in idruStrList2)
                        {
                            idruList.Add(int.Parse(id));
                        }
                        policestreetService = ServiceFactory.CreateService<IPoliceStreetService>();
                        policestreetService.RemoveStreet(Int32.Parse(areaId2), idruList);
                        ReturnSuccessMessage("移除街道成功");

                    }
                    catch (Exception ex)
                    {

                    }
                    break;
                case "DeletePoliceStreet":
                    try
                    {                                 
                        if (string.IsNullOrEmpty(Data))
                        {
                            throw new Exception("传入的选中用户Id为空");
                        }
                        List<int> idruList = new List<int>();
                        string[] idruStrList2 = Data.Split(',');
                        foreach (string id in idruStrList2)
                        {
                            idruList.Add(int.Parse(id));
                        }
                        policestreetService = ServiceFactory.CreateService<IPoliceStreetService>();
                        policestreetService.Delete(idruList);
                        ReturnSuccessMessage("移除街道成功");

                    }
                    catch (Exception ex)
                    {

                    }
                    break;



            }
        }

        private void GetOrganization(IOrganization organization, IList<IOrganization> list)
        {
            if (organization.Children.Count == 0)
            {
                list.Add(organization);
                return;
            }
            else
            {
                foreach (IOrganization item in organization.Children)
                {
                    GetOrganization(item, list);
                }
            }

        }



        private IList<IPoliceStreet> GetResponsibilityAreaStreetsByPoliceID(int policeManId, out int totalCount)
        {
            int rasId = policeManId;
            IPoliceStreetService responsibilityAreaStreetService = ServiceFactory.CreateService<IPoliceStreetService>();
            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true };
            Condition orgCondition = new Condition { Field = "PoliceMan.Id", Type = typeof(Int32).FullName, Value1 = rasId, Relation = Relations.And };
            group.Conditions.Add(enableCondition);
            group.Conditions.Add(orgCondition);
            IList<IPoliceStreet> list = responsibilityAreaStreetService.Search(group, null, PageSize, SelfPage, out totalCount);

            return list;
        }
    }
    public class ResponsibilityAreaStreetView
    {
        public int Id { get; set; }
        public int ResponsibilityAreaId { get; set; }
        public int StreetId { get; set; }
        public int PoliceMan { get; set; }
    }
}